# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 09:56:42 2020

@author: Administrator
"""

import json
import requests
import csv


def get_movie(typ, number):
    url = "https://movie.douban.com/tag/#/?sort=U&range=0,10&tags="
    headers = {"Users-Agent": "Mozilla/5.0"}
    params = {
        "type": typ,
        "interval_id": "100:90",
        "action": "",
        "start": "0",
        "limit": number
    }

    res = requests.get(url, params=params, headers=headers)
    res.encoding = "utf-8"
    # html 为json数组 [{}, {}, {}...]
    html = res.text
    # 数组 -> 列表
    html = json.loads(html)
    # 用for循环遍历每一个电影信息{}
    for film in html:
        L = [film["title"], film["rating"][0]]
        # {"rating":["9.6","50"],...}
        with open("douban.csv", "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow(L)


dic = {
    "剧情": "11",
    "喜剧": "%E5%96%9C%E5%89%A7",
    "动作": "5",
    "爱情": "13",
    "动画": "25",
    "惊悚": "19",
    "科幻": "17",
}
cmd = input("请输入电影类型：")
try:
    cmd = cmd.strip()
    get_movie(dic[cmd], input("请输入数量："))
except KeyError:
    print("类型不存在")
else:
    print("爬取成功呢")